package com.cm.servlet;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;

@WebServlet("/img")
@MultipartConfig
public class ImageUploadServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取上传文件的部分
        Part filePart = request.getPart("image");

        // 获取文件名
        String fileName = extractFileName(filePart);

        // 设置保存文件的位置
        String savePath = "C:\\temp\\" + fileName;

        // 将文件保存到指定位置
        InputStream fileContent = filePart.getInputStream();
        File file = new File(savePath);
        IOUtils.copy(fileContent, new FileOutputStream(file));
        fileContent.close();

        // 响应成功信息
        response.getWriter().println("File uploaded successfully to: " + savePath);
    }

    private String extractFileName(Part part) {
        // 提取文件名
        String contentDisp = part.getHeader("content-disposition");
        String[] items = contentDisp.split(";");
        for (String s : items) {
            if (s.trim().startsWith("filename")) {
                return s.substring(s.indexOf("=") + 2, s.length() - 1);
            }
        }
        return null;
    }
}